//
//  HMNetworkTools.swift
//  07-Swift网络访问
//
//  Created by teacher on 2017/6/5.
//  Copyright © 2017年 teacher. All rights reserved.
//

import UIKit
import AFNetworking
//  网络请求类型
enum RequestType {
    // get请求
    case get
    // post请求
    case post
}

class HMNetworkTools: AFHTTPSessionManager {
    //  单例的全局访问点,在swift里面没有manager方法，可以使用init方法，一样的
    static let sharedTools: HMNetworkTools = {
        let tools = HMNetworkTools()
        //  mutating 这个关键字表示插入的数据影响set集合
        //  添加可接收的服务端数据类型
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    //  通用网络请求封装方法
    fileprivate func requestData(type: RequestType, urlStr: String, params: Any?, callBack: @escaping (Any?, Error?)->()) {
        if type == .get {
            get(urlStr, parameters: params, progress: nil, success: { (_, responseObject) in
                callBack(responseObject, nil)
            }, failure: { (_, error) in
                callBack(nil, error)
            })
        } else {
            post(urlStr, parameters: params, progress: nil, success: { (_, responseObject) in
                callBack(responseObject, nil)
            }, failure: { (_, error) in
                callBack(nil, error)
            })
        }
    }
}

//  MARK:   --发微博相关接口
extension HMNetworkTools {
    
    
    /// 发送带有图片的微博
    ///
    /// - Parameters:
    ///   - token: 令牌
    ///   - status: 微博内容
    ///   - pic: 微博图片
    ///   - callBack: 闭包回调
    func sendMessage(token: String, status: String, pic: UIImage, callBack: @escaping (Any?, Error?) -> ()) {
        //  请求地址
        let urlStr = "https://upload.api.weibo.com/2/statuses/upload.json"
        //  请求参数
        let params = [
            "access_token": token,
            "status": status
        ]
        //  图片转成二进制，非常重要
//        let imageData = UIImagePNGRepresentation(pic)!
        //  compressionQuality: 图片的质量系数0-1， 质量系统越大图片越清晰，图片就越大
        //  如果图片质量要求不高可以使用UIImageJPEGRepresentation
        let imageData = UIImageJPEGRepresentation(pic, 0.5)!
        //  写入桌面查看图片简介
//        try! imageData.write(to: URL(fileURLWithPath: "/Users/teacher/Desktop/1.png"))
//        try! imageData1.write(to: URL(fileURLWithPath: "/Users/teacher/Desktop/2.png"))
        post(urlStr, parameters: params, constructingBodyWith: { (formData) in
            //  FileData: 图片的二进制
            //  name: 服务器端定义的参数名
            //  fileName: 图片名，可以随便写，服务端会自动创建一个唯一图片名
            //  mimeType: 文件的类型
            formData.appendPart(withFileData: imageData, name: "pic", fileName: "test", mimeType: "image/jpeg")
        }, progress: nil, success: { (_, response) in
            callBack(response, nil)
        }) { (_, error) in
            callBack(nil, error)
        }
    }
    
    /// 发送文字微博
    ///
    /// - Parameters:
    ///   - token: 令牌
    ///   - status: 微博内容
    ///   - callBack: 闭包回调
    func sendMessage(token: String, status: String, callBack: @escaping (Any?, Error?) -> ()) {
        //  请求地址
        let urlStr = "https://api.weibo.com/2/statuses/update.json"
        //  请求参数
        let params = [
            "access_token": token,
            "status": status
        ]
        //  执行网络请求
        requestData(type: .post, urlStr: urlStr, params: params, callBack: callBack)
    }
}

//  MARK:   --首页相关接口
extension HMNetworkTools {
    
    /// 获取登录用户及其所关注的微博数据
    ///
    /// - Parameters:
    ///   - token: 令牌
    ///   - maxId: 如果maxId大于0才会加载历史的微博数据
    ///   - sinceId: 如果maxId大于0才会加载最新的微博数据
    ///   - callBack: 闭包回调
    ///   - 提示: 如果sinceId为0 和 maxId 为0, 它会加载最新的二十条微博数据
    func requestStatuses(token: String, maxId: Int64 = 0, sinceId: Int64 = 0, callBack: @escaping (Any?, Error?) -> ()) {
        //  接口地址
        let urlStr = "https://api.weibo.com/2/statuses/home_timeline.json"
        //  请求参数
        let params: [String: Any] = [
            "access_token": token,
            "max_id": maxId,
            "since_id": sinceId
        ]
        print("\(urlStr)?access_token=\(token)")
        //  发送网络请求
        requestData(type: .get, urlStr: urlStr, params: params, callBack: callBack)
    }
}


//  MARK:   --OAuth相关接口
extension HMNetworkTools {
    
    /// 获取用户信息
    ///
    /// - Parameters:
    ///   - token: 令牌
    ///   - uid: 用户id
    ///   - callBack: 闭包回调
    func requestUserInfo(token: String, uid: Int64, callBack: @escaping (Any?, Error?) -> ()) {
        //  请求地址
        let urlStr = "https://api.weibo.com/2/users/show.json"
        //  请求参数
        let parms: [String: Any] = [
            "access_token": token,
            "uid": uid
        ]
        //  发送请求
        requestData(type: .get, urlStr: urlStr, params: parms, callBack: callBack)
    }
    
    /// 请求token
    ///
    /// - Parameters:
    ///   - code: 授权码
    ///   - callBack: 回调闭包
    func requestAccessToken(code: String, callBack: @escaping (Any?, Error?) -> ()) {
        //  请求地址
        let urlStr = "https://api.weibo.com/oauth2/access_token"
        //  请求参数
        let params = [
            "client_id": AppKey,
            "client_secret": AppSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": Redirect_Uri
        ]
        requestData(type: .post, urlStr: urlStr, params: params, callBack: callBack)
    }
    
    
}



